import React from 'react';
import { Descriptions, Form, Input, Radio, Checkbox, Select, Button, Rate, Modal } from 'antd';
import { connect } from 'dva';
import orderStatus from '../../common/database';
import { makeAppointment, administratorsSa } from '../../services/API';
import { message } from 'antd';

import styles from './index.less';
const { confirm } = Modal;
const { Option } = Select;
const { TextArea } = Input;
const namespace = 'returnManagement';
/**
 *  登录界面
 */
@connect(({ loading, returnManagement }) => ({
  detailData: returnManagement.curItem,
  //控制状态，绑定事件
  submitting: loading.effects['login/doLogin']
}))
@Form.create()
class OrderDetail extends React.Component {
  state = {
    value: 1,
    showTrextArea: false, //是否显示trextArea,
    needPay: false,
    btnLoading: false,
    approveReturnRequest: null
  };
  handleChange(value) {
    console.log(`selected ${value}`);
  }
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      this.showConfirm(err, values);
    });
  }
  async componentDidMount() {
    let userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      const roleId = userInfo.roles[0].roleId;
      let resp = await administratorsSa();
      if (resp && resp.code === 200) {
        const data = resp.data;
        for (let i = 0, ii; (ii = data[i++]); ) {
          if (ii.roleId === roleId) {
            this.setState({
              approveReturnRequest: ii.approveReturnRequest
            });
            return;
          }
        }
      }
    }
  }
  showConfirm(err, values) {
    var _this = this;
    confirm({
      // title: 'Do you Want to delete these items?',
      content: 'Approve request?',
      cancelText: 'No',
      okText: 'Yes',
      onOk() {
        console.log('OK', values);
        if (!err) {
          console.log(_this, 'this', _this.props.detailData);
          let reasonsForRejection = '';
          values.reasonsForRejection.map((item, index) => {
            reasonsForRejection += item + '#';
            if (index === values.reasonsForRejection.length - 1) {
              reasonsForRejection += item;
            }
          });
          values.reasonsForRejection = reasonsForRejection;
          _this.props.dispatch({
            type: `${namespace}/updateOrders`,
            payload: {
              ...values,
              status: 2,
              returnNo: _this.props.detailData.returnNo
            }
          });
        }
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  }
  handleCancle() {
    var _this = this;
    confirm({
      // title: 'Do you Want to delete these items?',
      content: 'Are you sure you want to reject this request?',
      cancelText: 'No',
      okText: 'Yes',
      onOk() {
        _this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            console.log(_this, 'this', _this.props.detailData);
            let reasonsForRejection = '';
            values.reasonsForRejection.map((item, index) => {
              reasonsForRejection += item + '#';
              if (index === values.reasonsForRejection.length - 1) {
                reasonsForRejection += item;
              }
            });
            values.reasonsForRejection = reasonsForRejection;
            _this.props.dispatch({
              type: `${namespace}/updateOrders`,
              payload: {
                ...values,
                status: 5,
                returnNo: _this.props.detailData.returnNo
              }
            });
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  }
  onChange = e => {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value
    });
  };
  async doRefund() {
    if (!this.props.detailData) return;
    this.setState({
      btnLoading: true
    });
    const result = await makeAppointment({
      returnNo: this.props.detailData.returnNo,
      status: 6
    });
    this.setState({
      btnLoading: false
    });
    if (result.code === 200) {
      message.success('Operation succeeded');
      this.props.dispatch({
        type: `${namespace}/fetch`,
        payload: {}
      });
      this.props.dispatch({
        type: `${namespace}/save`,
        payload: {
          showDrawer: false
        }
      });
    }
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { detailData } = this.props;
    const { showTrextArea, approveReturnRequest } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 6 }
      }
    };
    const optionsWithDisabled = [
      { label: 'The product has obvious stains', value: 'The product has obvious stains' },
      {
        label: 'Product photo is not clear-please take more photos',
        value: 'Product photo is not clear - plaease take more photos'
      },
      {
        label: 'Photo do not match the order-please take more photos',
        value: 'Photos do not match the order - please take more photos'
      },
      { label: 'No package', value: 'No package' },
      { label: 'Other reasons, please specify', value: 'Other reasons, please specify' }
    ];
    return (
      <div className={styles.approvedDetail}>
        <h3>Return number:{detailData ? detailData.returnNo : ''}</h3>
        <div className={styles.info}>
          <div className={styles.infoItem}>
            <div className={styles.name}>Order number</div>
            <div className={styles.txt}>{detailData ? detailData.orderNumber : ''}</div>
          </div>
          <div className={styles.infoItem}>
            <div className={styles.name}>Approval deadline</div>
            <div className={styles.txt}>{detailData ? detailData.approvalDeadline : ''}</div>
          </div>
          <div className={styles.infoItem}>
            <div className={styles.name}>Status</div>
            <div className={styles.txt} style={{ color: orderStatus[(detailData && detailData.status) || 0].color }}>
              {detailData && detailData.status ? orderStatus[detailData.status].value : orderStatus[1].value}
            </div>
          </div>
          <div className={styles.infoItem}>
            <div className={styles.name}>Approved by</div>
            <div className={styles.txt}>{detailData ? detailData.approvedBy : ''}</div>
          </div>
        </div>
        <div className={styles.company}>
          <div className={styles.name}>Company</div>
          <div className={styles.text}>{detailData ? detailData.company : ''}</div>
        </div>
        <div className={styles.product}>
          <div className={styles.title}>Product</div>
          <div className={styles.content}>
            <img src={detailData ? detailData.picPath : ''} className={styles.poster} alt="" />
            <div className={styles.detail}>
              <div className={styles.text}>{detailData ? detailData.productName : ''}</div>
              <div className={styles.text}>{detailData ? detailData.contactName : ''}</div>
              <div className={styles.tips}>{detailData ? detailData.size : ''}</div>
            </div>
          </div>
        </div>
        <Descriptions column={1}>
          <Descriptions.Item label="Estimated Refund" style={{ fontWeght: 'bold' }}>
            ${detailData ? detailData.estimatedRefund : 0.0}
          </Descriptions.Item>
          <Descriptions.Item label="Order payment">${detailData ? detailData.orderPaymen : 0.0}</Descriptions.Item>
          <Descriptions.Item label="Standard Delivery charge">
            ${detailData ? detailData.standardDeliveryCharge : 0.0}
          </Descriptions.Item>
          <Descriptions.Item label="Return cost">${detailData ? detailData.returnCost : 0.0}</Descriptions.Item>
        </Descriptions>
        <Descriptions title="Contact information" column={1}>
          <Descriptions.Item label="Name">{detailData ? detailData.contactName : ''}</Descriptions.Item>
          <Descriptions.Item label="Contact number">{detailData ? detailData.contactNumber : ''}</Descriptions.Item>
          <Descriptions.Item label="Email">{detailData ? detailData.email : ''}</Descriptions.Item>
          <Descriptions.Item label="Address">{detailData ? detailData.contactAddress : ''}</Descriptions.Item>
        </Descriptions>
        <div className={styles.reason}>
          <h3>Reason for Return</h3>
          {detailData && detailData.returnReason && detailData.returnReason.indexOf('#') > -1 ? (
            detailData.returnReason.split('#').map((item, index) => {
              return (
                <div key={index} className={styles.text}>
                  -{item || ''}
                </div>
              );
            })
          ) : (
            <div key={0} className={styles.text}>
              -{detailData ? detailData.returnReason : ''}
            </div>
          )}
        </div>
        <br></br>

        <div className={styles.photos}>
          <h3>Photos provided by the customer(click to view)</h3>
          <div className={styles.imgList}>
            {detailData && detailData.trcUploadPhoto && detailData.trcUploadPhoto.indexOf(',') > -1 ? (
              detailData.trcUploadPhoto.split(',').map((item, index) => {
                return (
                  <div className={styles.imgItem} key={item}>
                    <img src={item} alt="" className={styles.imgItem} />
                    <div className={styles.imgName}>{index === 0 ? 'Front' : 'Side'}</div>
                  </div>
                );
              })
            ) : (
              <div className={styles.imgItem}>
                <img src={(detailData && detailData.trcUploadPhoto) || ''} alt="" className={styles.imgItem} />
                <div className={styles.imgName}>Front</div>
              </div>
            )}
          </div>
        </div>
        {detailData && (detailData.status === 8 || detailData.status === 6) && detailData.trcUploadPhoto && (
          <div className={styles.photos}>
            <h3>Logistics pick-up photos</h3>
            <div className={styles.imgList}>
              {detailData && detailData.trcUploadPhoto && detailData.trcUploadPhoto.indexOf(',') > -1 ? (
                detailData.trcUploadPhoto.split(',').map(item => {
                  return (
                    <div className={styles.imgItem} key={item}>
                      <img src={item} alt="" className={styles.imgItem} />
                      <div className={styles.imgName}>Front</div>
                    </div>
                  );
                })
              ) : (
                <div className={styles.imgItem}>
                  <img src={(detailData && detailData.trcUploadPhoto) || ''} alt="" className={styles.imgItem} />
                  <div className={styles.imgName}>Front</div>
                </div>
              )}
            </div>
          </div>
        )}
        {detailData && (detailData.status === 8 || detailData.status === 6) && (
          <div className={styles.photos}>
            <h3>Customer signature</h3>
            <div className={styles.imgList}>
              {detailData && detailData.unOpenedPackage && detailData.unOpenedPackage.indexOf(',') > -1 ? (
                detailData.unOpenedPackage.split(',').map(item => {
                  return (
                    <div key={item} className={styles.imgItem} style={{ width: '160px' }}>
                      <img src={item} alt="" className={styles.imgItem} />
                    </div>
                  );
                })
              ) : (
                <div className={styles.imgItem} style={{ width: '160px' }}>
                  <img src={(detailData && detailData.unOpenedPackage) || ''} alt="" className={styles.imgItem} />
                </div>
              )}
            </div>
          </div>
        )}
        <Form {...formItemLayout} className="orderDetailForm" onSubmit={this.handleSubmit.bind(this)}>
          <Form.Item label="Item condition">
            {getFieldDecorator('itemCondition', {
              initialValue: 'New in box"'
            })(
              <Select style={{ width: 200 }}>
                <Option value="New in box">New in box</Option>
                <Option value="Like new: Open box">Like new: Open box</Option>
                <Option value="Good:Slightly damaged">Good:Slightly damaged</Option>
                <Option value="Big defects but usable">Big defects but usable</Option>
                <Option value="Salvage:not uesble">Salvage:not uesble</Option>
              </Select>
            )}
          </Form.Item>
          <Form.Item className="originalPackage" label="With original package">
            {getFieldDecorator('originalPackage', {
              initialValue: detailData ? detailData.returnPackage : 1
            })(
              <Radio.Group disabled>
                <Radio value={0}>Yes</Radio>
                <Radio value={1}>No</Radio>
              </Radio.Group>
            )}
          </Form.Item>

          <div>
            <Form.Item>
              {getFieldDecorator('isNeedToPay', {
                initialValue: false
              })(
                <Checkbox
                  onChange={event => {
                    if (event.target.checked) {
                      // console.log(this.props.form,'333');
                      this.props.form.setFieldsValue({
                        noNeedToPay: false
                      });
                    }
                  }}
                >
                  Need to pay for the packing
                </Checkbox>
              )}
            </Form.Item>
            {this.props.form.getFieldValue('isNeedToPay') && (
              <Form.Item label="Payment amount">
                {getFieldDecorator('needToPay', {
                  initialValue: detailData ? detailData.packingCost : ''
                })(<Input prefix="$" />)}
              </Form.Item>
            )}
            {/* <Form.Item>
              {getFieldDecorator('noNeedToPay', {
                initialValue: false,
              })(<Checkbox onChange={(event) => {
                if (event.target.checked) {
                  console.log(this.props.form, '333');
                  this.props.form.setFieldsValue({
                    isNeedToPay: false
                  })
                }
              }}>No pay for the packing</Checkbox>)}
            </Form.Item> */}
          </div>

          <Form.Item className="damaged" label="Whether the goods are damaged">
            {getFieldDecorator('goodsAreDamaged', {
              initialValue: detailData ? detailData.damageOrNot : 1
            })(
              <Radio.Group disabled>
                <Radio value={0}>Yes</Radio>
                <Radio value={1}>No</Radio>
              </Radio.Group>
            )}
          </Form.Item>
          {this.props.form.getFieldValue('goodsAreDamaged') === 0 ? (
            <Form.Item className="Refund" label="Refund">
              {getFieldDecorator('goodsValue', {
                initialValue: detailData ? detailData.damagedCost : ''
              })(
                <div className={styles.refund}>
                  <Input style={{ width: '140px' }} /> % of the goods value
                </div>
              )}
            </Form.Item>
          ) : (
            ''
          )}

          <Form.Item
            className="rejection"
            label="Reasons for rejection (Please select the reject reason if you want to reject the return request )"
          >
            {getFieldDecorator('reasonsForRejection', {
              initialValue: []
            })(
              <Checkbox.Group
                width={'100%'}
                options={optionsWithDisabled}
                onChange={values => {
                  this.setState({
                    showTrextArea: values.includes('Other reasons,please specify')
                  });
                }}
              />
            )}
          </Form.Item>
          {showTrextArea && (
            <Form.Item label="">
              {getFieldDecorator('trextArea', {
                initialValue: ''
              })(<TextArea rows={4} />)}
            </Form.Item>
          )}

          {detailData && detailData.status === 6 && (
            <div>
              <h3>Customer evaluation</h3>
              <Form.Item label="Clear Retuen Policy">
                {getFieldDecorator('rate1', {
                  initialValue: ''
                })(<Rate />)}
              </Form.Item>
              <Form.Item label="Timely Return Approval">
                {getFieldDecorator('rate2', {
                  initialValue: ''
                })(<Rate />)}
              </Form.Item>
              <Form.Item label="Easy to Return">
                {getFieldDecorator('rate3', {
                  initialValue: ''
                })(<Rate />)}
              </Form.Item>
            </div>
          )}

          {detailData && detailData.status === 1 && approveReturnRequest ? (
            <Form.Item className={styles.btnList}>
              <Button onClick={() => this.handleCancle()} className={styles.formBtn}>
                Reject
              </Button>
              <Button htmlType="submit" className="formBtns">
                Approve
              </Button>
            </Form.Item>
          ) : null}
          {detailData && detailData.status === 5 && approveReturnRequest ? (
            <Form.Item className={styles.btnList}>
              <Button htmlType="submit" className="formBtns">
                Re-approve
              </Button>
            </Form.Item>
          ) : null}
          {detailData && detailData.status === 8 ? (
            <Form.Item className={styles.btnList}>
              <Button
                loading={this.state.btnLoading}
                className="formBtns"
                onClick={() => {
                  this.doRefund();
                }}
              >
                Refund
              </Button>
            </Form.Item>
          ) : null}
        </Form>
      </div>
    );
  }
}
export default OrderDetail;
